import { queryAll, remove, query } from '../services/contract'
import { message } from 'antd'

export default {

  namespace: 'contract',

  state: {
    load : true,
    list: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        const pathname = location.pathname
        if(pathname === '/contract'){
          dispatch({
            type: 'query',
            payload: location.query,
          })
        }
      })
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {  // eslint-disable-line
      yield put({ type: 'save' });
    },
    *query({ payload }, { call, put }){
      const data = yield call(queryAll)
      yield put ({type: 'hideLoading'})

      if(data){
        yield put({
          type: 'querySuccess',
          payload: {
            list: data,
          },
        })
      }
    },
    *'delete' ({ payload }, { call, put }) {
      const data = yield call(remove, { payload })
      if(data){
        yield put({
          type: 'querySuccess',
          payload: {
            list: data,
          },
        })
        message.success('删除成功！',1)
      }
    },
    *search({ payload }, {call, put }){
      const data = yield call(query, payload);
      if(data){
        yield put({
          type: 'querySuccess',
          payload: {
            list: data,
          },
        })
      }
    }

  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },

    querySuccess (state, action) {
      const { list } = action.payload
      return { ...state,
        list,
       }
    },

    //隐藏加载
    hideLoading (state,action) {
      return {
        load: false
      }
    },

  },
};
